//
//  EmailLoginView.m
//  QRMaster
//
//  Created by myApple on 16/3/2.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "EmailLoginView.h"
#import "LineView.h"
#import "PromptInfoView.h"
#import "validateInputValue.h"

@interface EmailLoginView()<UITextFieldDelegate>
{
    UIImageView * TitleImgView;
    UIButton * AreaTextBtn;
    UITextField * UserNameTextField;
    UITextField * PassWordTextField;
    UIButton * ForgetBnt;
    UIButton * LoginBtn;
    UIButton * newSeeBtn;
    
    LineView * userNameLine;
    LineView * passWordLine;
    
    BOOL emailFlag;
    BOOL passWordFlag;
}

@end

@implementation EmailLoginView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        emailFlag = NO;
        passWordFlag = NO;
        [self prepareView];
    }
    return self;
}

-(void)prepareView
{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(hiddenKeyboard) name:@"KCHiddenKeyBoardNotification" object:nil];
    float ScreenWidth = self.frame.size.width;
//    float ScreenHeight = self.frame.size.height;
    float x = 95;
    float y = 71;
    float width = ScreenWidth - x - 16;
    float height = 39;
    
    UserNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    UserNameTextField.placeholder = NSLocalizedString(@"mineEmail", nil);
    UserNameTextField.font = [UIFont systemFontOfSize:13.0];
    UserNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    UserNameTextField.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [self addSubview:UserNameTextField];
    UserNameTextField.delegate = self;
//    UIImageView * userNameView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
//    UIImage * userimag = [UIImage imageNamed:@"36登录_用户"];
//    userNameView.image = userimag;
    UILabel * emailLabel = [[UILabel alloc]initWithFrame:CGRectMake(22, y + 10, 70, 20)];
    emailLabel.text = NSLocalizedString(@"mineEmail", nil);
    emailLabel.font = [UIFont systemFontOfSize:13.0];
    [self addSubview:emailLabel];
//    UserNameTextField.leftView = userNameView;
//    UserNameTextField.leftViewMode = UITextFieldViewModeAlways;
    userNameLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, UI_SCREEN_WIDTH - 32, 0.5)];
    userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:userNameLine];
    
    y += height;
    PassWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(x, y, width, height)];
    PassWordTextField.secureTextEntry = YES;
    PassWordTextField.placeholder = NSLocalizedString(@"passPromt", nil);
    PassWordTextField.delegate = self;
    PassWordTextField.font = [UIFont systemFontOfSize:13.0];
    PassWordTextField.borderStyle = UITextBorderStyleNone;
    PassWordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self addSubview:PassWordTextField];
    passWordLine = [[LineView alloc]initWithFrame:CGRectMake(16, y+height, UI_SCREEN_WIDTH - 32, 0.5)];
    passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    [self addSubview:passWordLine];
    
    UIImageView * newSeeImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    PassWordTextField.rightViewMode = UITextFieldViewModeAlways;
    PassWordTextField.rightView = newSeeImgView;
    newSeeImgView.userInteractionEnabled = YES;
    UITapGestureRecognizer * newSeeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(seeNewTap)];
    [newSeeImgView addGestureRecognizer:newSeeTap];
    newSeeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    newSeeBtn.frame = CGRectMake(12, 14, 16, 12);
    newSeeBtn.selected = NO;
    newSeeBtn.userInteractionEnabled = NO;
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"Browse"] forState:UIControlStateNormal];
    [newSeeBtn setBackgroundImage:[UIImage imageNamed:@"GreenBrowse"] forState:UIControlStateSelected];
    [newSeeImgView addSubview:newSeeBtn];
    
//    UIImageView * passWordView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 10, 20, 20)];
//    UIImage * passWordImg = [UIImage imageNamed:@"36登录_密码"];
//    passWordView.image = passWordImg;
//    PassWordTextField.leftView = passWordView;
//    PassWordTextField.leftViewMode = UITextFieldViewModeAlways;
    UILabel * passWordLabel =[[UILabel alloc]initWithFrame:CGRectMake(22, y + 10, 70, 20)];
    passWordLabel.text = NSLocalizedString(@"passWord", nil);
    passWordLabel.font = [UIFont systemFontOfSize:13.0];
    [self addSubview:passWordLabel];
    
    x = 16;
    y += height + 20;
    width = ScreenWidth - 2 * x;
    height = 40;
    LoginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    LoginBtn.frame = CGRectMake(x, y, width, height);
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff, 0.5) forState:0];
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7dc234, 0.5)];
    [LoginBtn setTitle:NSLocalizedString(@"loginBtn", nil) forState:0];
    LoginBtn.layer.cornerRadius = 5;
    LoginBtn.titleLabel.font = [UIFont systemFontOfSize:19.0];
    LoginBtn.enabled = NO;
    [LoginBtn addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:LoginBtn];
    
    
    y = LoginBtn.frame.size.height + LoginBtn.frame.origin.y + 10;
    height = 40;
    x = UI_SCREEN_WIDTH - 152;
    width = 130;
    ForgetBnt = [UIButton buttonWithType:UIButtonTypeCustom];
    ForgetBnt.frame = CGRectMake(x, y, width, height);
    [ForgetBnt setTitle:NSLocalizedString(@"forgetBtn", nil) forState:0];
    ForgetBnt.titleLabel.font = [UIFont systemFontOfSize:12.0];
    [ForgetBnt setTitleColor:UIColorFromRGB(0x7dc234) forState:0];
    [ForgetBnt setBackgroundColor:[UIColor clearColor]];
    ForgetBnt.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [ForgetBnt addTarget:self action:@selector(forgetClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:ForgetBnt];
    
}

#pragma mark ----------- textFieldDelegate
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        userNameLine.backgroundColor = UIColorFromRGB(0x7dc234);
        passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    }
    else if (textField == PassWordTextField) {
        passWordLine.backgroundColor = UIColorFromRGB(0x7dc234);
        userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
    }
    
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if (textField == PassWordTextField) {
        userNameLine.backgroundColor = UIColorFromRGB(0x7dc234);
        passWordLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
        PassWordTextField.text = textField.text;
    }
    else if(textField == UserNameTextField)
    {
        passWordLine.backgroundColor = UIColorFromRGB(0x7dc234);
        userNameLine.backgroundColor = UIColorFromRGB(0xc1c1c1);
        UserNameTextField.text = textField.text;
    }
}

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
     NSString * newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == UserNameTextField) {
        if (newString.length > 0) {
            emailFlag = YES;
        }
        else
        {
            emailFlag = NO;
        }
    }
    else if (textField == PassWordTextField)
    {
        if (newString.length > 0) {
            passWordFlag = YES;
        }
        else
        {
            passWordFlag = NO;
        }
    }
    [self canTapOfRegist];
    return YES;
}


-(BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == UserNameTextField) {
        emailFlag = NO;
    }
    else if (textField == PassWordTextField)
    {
        passWordFlag = NO;
    }
    [self canTapOfRegist];
    return YES;
}

-(void)forgetClick:(UIButton *)btn
{
    if (_delegate && [_delegate respondsToSelector:@selector(emailForgetPassWord)]) {
        [_delegate emailForgetPassWord];
    }
}


-(void)loginClick:(UIButton *)btn
{
    UserNameTextField.text = [UserNameTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
    if (![validateInputValue validateStringIsNull:UserNameTextField.text])
    {
        if (![validateInputValue validateEmail:UserNameTextField.text])
        {
            [PromptInfoView showMessage:NSLocalizedString(@"AccountError", nil)];
            return;
        }
    }
    else
    {
        [PromptInfoView showMessage:NSLocalizedString(@"errorAccount", nil)];
        return;
    }
    
    if (![validateInputValue validatePassword:PassWordTextField.text]) {
        [PromptInfoView showMessage:NSLocalizedString(@"loginingPromt", nil)];
        return;
    }

    if (_delegate && [_delegate respondsToSelector:@selector(EmailLogin:PassWord:)]) {
        [_delegate EmailLogin:UserNameTextField.text PassWord:PassWordTextField.text];
    }
}

#pragma mark --------看密码
-(void)seeNewTap
{
    newSeeBtn.selected = !newSeeBtn.selected;
    if (newSeeBtn.selected) {
        PassWordTextField.secureTextEntry = NO;
    }
    else
    {
        PassWordTextField.secureTextEntry = YES;
    }
}

#pragma mark ----------- 判断注册按钮是否能够点击
-(void)canTapOfRegist
{
    if (emailFlag && passWordFlag) {
        [self loginBtnEnable];
    }
    else
    {
        [self loginBtnDisenable];
    }
}


#pragma mark ----------注册按钮点击和不可以点击的两种状态
-(void)loginBtnEnable
{
    [LoginBtn setBackgroundColor:UIColorFromRGB(0x7cd234)];
    [LoginBtn setTitleColor:UIColorFromRGB(0xffffff) forState:0];
    LoginBtn.enabled = YES;
}

-(void)loginBtnDisenable
{
    [LoginBtn setBackgroundColor:UIColorFromRGBAndA(0x7cd234, 0.5)];
    [LoginBtn setTitleColor:UIColorFromRGBAndA(0xffffff,0.5) forState:0];
    LoginBtn.enabled = NO;
}


-(void)hiddenKeyboard
{
    [UserNameTextField resignFirstResponder];
    [PassWordTextField resignFirstResponder];
}

#pragma mark -- roomNo自适应长度
-(CGFloat)calculateWidth:(NSString *)str
{
    CGSize size =CGSizeMake(self.frame.size.width,20);
    
    NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12.0],NSFontAttributeName,nil];
    
    //ios7方法，获取文本需要的size，限制宽度
    
    CGSize  actualsize =[str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
    return actualsize.width;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"KCHiddenKeyBoardNotification" object:nil];
}


/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
